<template>
  <div class="app-container">
    <introduce :title="title" :content="content" />
    <div class="filter-container">
      <div>
        <el-form :inline="true" :model="listQuery" class="demo-form-inline">
          <el-form-item>
            <el-input v-model.trim="listQuery.username" size="small" placeholder="请输入用户名" />
          </el-form-item>
          <el-form-item>
            <el-input v-model.trim="listQuery.truename" size="small" placeholder="请输入姓名" />
          </el-form-item>
          <el-form-item>
            <el-input v-model.trim="listQuery.email" size="small" placeholder="请输入电子邮件" />
          </el-form-item>
          <el-form-item>
            <el-button type="danger" size="small" @click="getList">搜索</el-button>
            <el-button size="small" @click="resetList">重置</el-button>
          </el-form-item>
        </el-form>
      </div>
      <div>
        <el-button
          class="filter-item"
          style="margin-left: 10px"
          size="small"
          type="danger"
          icon="el-icon-edit"
          @click="createDialog()"
        >
          添加
        </el-button>
      </div>
    </div>

    <div class="table-wrapper">
      <el-table
        :key="tableKey"
        v-loading="listLoading"
        :data="list"
        size="small"
        border
        fit
        height="calc(100vh - 320px)"
        style="width: 100%"
      >
        <el-table-column label="用户名" prop="username" align="center">
          <template slot-scope="{ row }">
            <span>{{ row.username }}</span>
          </template>
        </el-table-column>
        <el-table-column label="状态" prop="status" align="center">
          <template slot-scope="{ row }">
            <el-tag :type="row.status ? statusArr[row.status].type : ''">{{ row.status | statusFilter }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="角色" prop="roleName" align="center">
          <template slot-scope="{ row }">
            <span>{{ row.roleName }}</span>
          </template>
        </el-table-column>
        <el-table-column label="姓名" prop="truename" align="center">
          <template slot-scope="{ row }">
            <span>{{ row.truename }}</span>
          </template>
        </el-table-column>
        <el-table-column label="邮箱" prop="email" align="center">
          <template slot-scope="{ row }">
            <span>{{ row.email }}</span>
          </template>
        </el-table-column>
        <el-table-column label="手机号">
          <template slot-scope="{ row }" prop="mobile" align="center">
            <span>{{ row.mobile }}</span>
          </template>
        </el-table-column>
        <el-table-column label="是否管理员" prop="adminStatus" align="center">
          <template slot-scope="{ row }">
            <el-tag :type="row.adminStatus | adminStatusFilter">{{ row.adminStatus ? '是' : '否' }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="创建时间" prop="createTime" align="center">
          <template slot-scope="{ row }">
            <span>{{ row.createTime }}</span>
          </template>
        </el-table-column>
        <el-table-column label="更新时间" prop="updateTime" align="center">
          <template slot-scope="{ row }">
            <span>{{ row.updateTime }}</span>
          </template>
        </el-table-column>
        <el-table-column label="描述" prop="description" header-align="center" min-width="160px">
          <template slot-scope="{ row }">
            <span>{{ row.description }}</span>
          </template>
        </el-table-column>
        <el-table-column
          label="操作"
          align="center"
          width="160"
          class-name="small-padding fixed-width"
        >
          <template slot-scope="{ row }">
            <div class="flex">
              <el-link type="primary" @click="handleUpdate(row)">编辑</el-link>
              <el-link type="primary" @click="handleDelete(row)">删除</el-link>
              <el-link type="primary" @click="handleCheck(row)">详情</el-link>
            </div>
          </template>
        </el-table-column>
      </el-table>

      <pagination
        v-show="total > 0"
        :total="total"
        :page.sync="listQuery.page"
        :limit.sync="listQuery.size"
        @pagination="getList"
      />
    </div>

    <el-drawer
      ref="drawer"
      size="30%"
      custom-class="demo-drawer"
      :title="textMap[dialogStatus]"
      :visible.sync="dialogFormVisible"
      :direction="direction"
    >
      <div :class="'demo-drawer__content el-details ' + dialogStatus">
        <el-form
          ref="dataForm"
          :rules="rules"
          :model="temp"
          label-width="100px"
        >
          <el-form-item label="用户名" prop="username">
            <el-input v-model.trim="temp.username" :disabled="dialogStatus!=='create'" />
          </el-form-item>
          <el-form-item v-if="dialogStatus==='create'" prop="password" label="密码">
            <el-input v-model.trim="temp.password" show-password />
          </el-form-item>
          <el-form-item key="selelctDept" label="部门" prop="projectId">
            <div class="treeWrapper">
              <el-tree
                ref="tree"
                node-key="id"
                :data="treeDept"
                :default-expanded-keys="expandedKey"
                accordion
                :check-on-click-node="true"
                :default-expand-all="true"
                :expand-on-click-node="false"
                :current-node-key="currentNodeKey"
                :highlight-current="treeHighlight"
                @node-click="handleNodeClick"
              />
            </div>
          </el-form-item>
          <el-form-item v-if="dialogStatus==='details'" label="角色" prop="roleName">
            <el-input v-model="temp.roleName" disabled />
          </el-form-item>
          <el-form-item v-if="dialogStatus!=='details'" label="选择角色" prop="roleId">
            <el-select
              v-model="temp.roleId"
              placeholder="请选择角色"
              class="filter-item"
            >
              <el-option
                v-for="item in roles"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="是否管理员" prop="adminStatus">
            <el-input v-if="dialogStatus==='details'" v-model="adminStatusArr[temp.adminStatus ? 0 : 1].name" disabled />
            <el-select
              v-else
              v-model="temp.adminStatus"
              placeholder="请选择状态"
              class="filter-item"
            >
              <el-option
                v-for="item in adminStatusArr"
                :key="item.key"
                :label="item.name"
                :value="item.key"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="姓名">
            <el-input v-model="temp.truename" :disabled="dialogStatus==='details'" />
          </el-form-item>
          <el-form-item label="邮箱">
            <el-input v-model="temp.email" :disabled="dialogStatus==='details'" />
          </el-form-item>
          <el-form-item label="手机号">
            <el-input v-model="temp.mobile" :disabled="dialogStatus==='details'" />
          </el-form-item>
          <el-form-item v-if="dialogStatus==='details'" label="创建时间" prop="createTime">
            <el-input v-model="temp.createTime" disabled />
          </el-form-item>
          <el-form-item v-if="dialogStatus==='details'" label="更新时间" prop="updateTime">
            <el-input v-model="temp.updateTime" disabled />
          </el-form-item>
          <el-form-item label="描述">
            <el-input
              v-model="temp.description"
              :autosize="{ minRows: 6, maxRows: 8 }"
              type="textarea"
              :disabled="dialogStatus==='details'"
            />
          </el-form-item>
        </el-form>
        <div class="demo-drawer__footer">
          <el-button v-if="dialogStatus !== 'details'" type="danger" @click="dialogStatus === 'create' ? createData() : updateData()">
            提交
          </el-button>
          <el-button v-if="dialogStatus !== 'details'" @click="dialogFormVisible = false"> 取消 </el-button>
          <el-button v-else @click="dialogFormVisible = false">
            关闭
          </el-button>
        </div>
      </div>
    </el-drawer>
  </div>
</template>

<script>
import Introduce from '@/layout/components/introduce'
import { listUser, createUser, editUser, deleteUser } from '@/api/user'
import { listRole } from '@/api/role'
import { listTreeProject } from '@/api/project'
import { transTreeData } from '@/utils/data'
import { validUsername, validatePsdReg, validatePhoneTwo, validateEMail } from '@/utils/validate'
import waves from '@/directive/waves'
import Pagination from '@/components/Pagination'

const statusArr = [
  {
    key: 0,
    value: '启用',
    type: 'success'
  },
  {
    key: 1,
    value: '停用',
    type: 'info'
  }
]
const adminStatusArr = [{
  key: true,
  name: '是',
  type: 'success'
}, {
  key: false,
  name: '否',
  type: 'info'
}]
export default {
  name: 'MetadataModel',
  components: { Introduce, Pagination },
  directives: { waves },
  filters: {
    statusFilter(status) {
      for (const item of statusArr) {
        if (item.key === parseInt(status)) {
          return item.value
        }
      }
    },
    adminStatusFilter(status) {
      for (const item of adminStatusArr) {
        if (item.key === status) {
          return item.type
        }
      }
    }
  },
  data() {
    return {
      title: '用户',
      content: '租户下的用户，包含对管理人员和普通用户的维护',
      tableKey: 0,
      list: null,
      total: 0,
      listLoading: true,
      project: [],
      adminStatusArr: [{
        key: true,
        name: '是'
      }, {
        key: false,
        name: '否'
      }],
      roles: [],
      listQuery: {
        page: 1,
        size: 10,
        domainId: null,
        username: null,
        truename: null,
        email: null
      },
      temp: {
        id: undefined,
        adminStatus: false,
        roleId: '',
        projectId: '',
        description: '',
        emali: '',
        mobile: '',
        password: '',
        status: 0,
        truename: '',
        username: ''
      },
      expandedKey: [],
      treeHighlight: true,
      currentNodeKey: '',
      treeDept: [
        // {
        //   label: '一级 1 - 1',
        //   children: [{
        //     label: '二级 1-1',
        //     children: [{
        //       label: '三级 1-1-1'
        //     }]
        //   }, {
        //     label: '二级 1-2',
        //     children: [{
        //       label: '三级 1-2-1'
        //     }]
        //   }]
        // }
      ],
      dialogStatus: 'create',
      textMap: {
        update: '编辑',
        create: '创建',
        details: '详情'
      },
      rules: {
        username: [{ required: true, trigger: 'blur', validator: validUsername }],
        projectId: [{ required: true, message: '请选择部门', trigger: 'blur' }],
        password: [{ required: true, trigger: 'blur', validator: validatePsdReg }],
        roleId: [{ required: true, trigger: 'blur', message: '请选择角色' }],
        mobile: [{ trigger: 'blur', validator: validatePhoneTwo }],
        email: [{ trigger: 'blur', validator: validateEMail }]
      },
      downloadLoading: false,
      dialogFormVisible: false,
      direction: 'rtl',
      disable: false
    }
  },
  created() {
    this.listQuery.domainId = this.$store.getters.userInfo.domainId
    this.temp.domainId = this.$store.getters.userInfo.domainId
    this.getList()
  },
  methods: {
    getDeptTree() {
      listTreeProject({
        domainId: this.$store.getters.userInfo.domainId,
        parent_id: -1
      }).then(response => {
        const treeData = response.data
        this.treeDept = transTreeData([], treeData)
        if (this.dialogStatus === 'update' || this.dialogStatus === 'details') {
          setTimeout(() => {
            this.currentNodeKey = this.temp.projectId
            this.$refs['tree'].setCurrentKey(this.currentNodeKey)
          }, 200)
        }
      })
    },
    handleNodeClick(data) {
      this.temp.projectId = data.id
    },
    getRoles() {
      listRole({
        page: 1,
        size: 1000,
        domainId: this.$store.getters.userInfo.domainId
      }).then(resp => {
        this.roles = resp.content
      })
    },
    resetList() {
      this.listQuery = {
        page: 1,
        size: 10,
        domainId: this.$store.getters.userInfo.domainId,
        username: null,
        truename: null,
        email: null
      }
      this.getList()
    },
    getList() {
      this.listLoading = true
      listUser(this.listQuery).then(response => {
        this.list = response.content
        this.total = response.totalPages
        this.listLoading = false
      })
    },
    resetTemp() {
      this.temp = {
        id: undefined,
        domainId: this.$store.getters.userInfo.domainId,
        roleId: '',
        adminStatus: false,
        description: '',
        projectId: '',
        emali: '',
        mobile: '',
        password: '',
        status: 0,
        truename: '',
        username: ''
      }
    },
    createDialog() {
      this.resetTemp()
      this.getRoles()
      this.getDeptTree()
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
    },
    createData() {
      this.$refs['dataForm'].validate(valid => {
        if (valid) {
          createUser(this.temp).then(resp => {
            this.dialogFormVisible = false
            this.$notify({
              title: '提示',
              message: '组织添加成功',
              type: 'success',
              duration: 2000
            })
            this.getList()
          })
        }
      })
    },
    handleUpdate(row) {
      this.temp = Object.assign({}, row) // copy obj
      this.getRoles()
      this.getDeptTree()
      this.dialogStatus = 'update'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    updateData() {
      this.$refs['dataForm'].validate(valid => {
        if (valid) {
          const tempData = Object.assign({}, this.temp)
          editUser(tempData.id, {
            adminStatus: this.temp.adminStatus,
            projectId: this.temp.projectId,
            description: this.temp.description,
            emali: this.temp.emali,
            mobile: this.temp.mobile,
            status: this.temp.status,
            truename: this.temp.truename,
            username: this.temp.username,
            roleId: this.temp.roleId
          }).then(() => {
            this.dialogFormVisible = false
            this.$notify({
              title: '提示',
              message: '更新成功',
              type: 'success',
              duration: 2000
            })
            this.getList()
          })
        }
      })
    },
    handleDelete(row) {
      this.$confirm('此操作将永久删除该用户, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          deleteUser(row.id).then(() => {
            this.$message({
              type: 'success',
              message: '删除成功!'
            })
            this.getList()
          })
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
    },
    handleCheck(row) {
      this.temp = Object.assign({}, row) // copy obj
      this.dialogStatus = 'details'
      this.dialogFormVisible = true
      this.getRoles()
      this.getDeptTree()
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.filter-container {
  display: flex;
  justify-content: space-between;
  padding-bottom: 0 !important;
  .filter-item:not(button) {
    margin-right: 10px;
  }
}
.create-model {
  padding: 0 20px;
  > div {
    padding: 20px 0;
  }
}
.demo-drawer__content {
  display: flex;
  flex-direction: column;
  height: 100%;
  padding: 20px 40px;
  form {
    flex: 1;
  }
  .demo-drawer__footer {
    display: flex;
    justify-content: center;
  }
}
.flex {
  display: flex;
  padding: 0 20px;
  justify-content: space-between;
}
</style>
